/*
* @Author: dengjiayao
* @Date:   2017-06-28 14:29:05
* @Last Modified by:   dengjiayao
* @Last Modified time: 2017-07-05 17:50:10
*/

import { modal } from 'vue-strap'

import { showMsg, qiniuUpload, addCastTalkAttactment } from '../../vuex/action'

export default {
  name: 'cast-talk-item-uploader',
  components: {
    'vue-modal': modal
  },
  data() {
    return {
      showModal: false,
      form: {
        id: null,
        name: '',
        url: ''
      }
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xUpload: qiniuUpload,
      xAdd: addCastTalkAttactment
    }
  },
  methods: {
    init(id) {
      this.$els.form.reset()
      this.form.id = id
      this.showModal = true
    },
    valid() {
      if (this.$els.file.files.length === 0) {
        return Promise.reject({
          msg: '请选择附件'
        })
      }
      if (this.form.name.length === 0) {
        return Promise.reject({
          msg: '请填写文件名'
        })
      }
      return Promise.resolve()
    },
    submit() {
      this.valid()
        .then(() => {
          let formData = new FormData()
          formData.append('extfile', this.$els.file.files[0])
          return this.xUpload(formData)
        })
        .then((res) => {
          this.form.url = res.data.url
          return this.xAdd(this.form)
        })
        .then(() => {
          this.showModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.msg || res.error_msg
          })
        })
    }
  }
}
